# coding=utf-8
from Database_Config import *
import tornado.ioloop
import tornado.web
import tornado.websocket
import datetime
import json
import sys
import time
import threading

clients = []

FILENAME = "logs/3000.log";
FORMAT = "%(asctime)-15s %(message)s"
logging.basicConfig(format = FORMAT, filename = FILENAME, level = logging.DEBUG)
RotatingFileHandler(FILENAME, mode='a', maxBytes=1*1024*1024,
                     backupCount=1, encoding=None, delay=0)

def updateClients():
    while True:
        try:
            dbc = conn_ibm_dbi.cursor()
            sql = "select TAGNAME, TAGVALUE, ID from UACS_WEB_TAG_WS;"
            dbc.execute(sql)
            rows = dbc.fetchall()
            if len(rows) is 0:
                time.sleep(0.100)
                continue
            data = {'data': rows}
            for c in clients:
                c.write_message(json.dumps(
                    data, indent=4, sort_keys=True, default=str, ensure_ascii=False).encode("utf8"))
            ids = "','".join([str(x[2]) for x in rows])
            sql = "delete from UACS_WEB_TAG_WS where ID in ('" + ids + "');"
            dbc.execute(sql)
            conn_ibm_dbi.commit()
            time.sleep(0.100)
        except Exception, ex:
            pass


class EchoWebSocket(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        clients.append(self)

    def on_message(self, message):
        self.write_message(u"You said: " + message)

    def on_close(self):
        clients.remove(self)


def make_app():
    return tornado.web.Application([
        (r"/", EchoWebSocket),
    ], debug=False)


if __name__ == "__main__":
    t = threading.Thread(target=updateClients)
    t.start()

    try:
        app = make_app()
        app.listen(sys.argv[1])
        tornado.ioloop.IOLoop.current().start()
    except Exception, ex:
        logging.error(ex)

